export function timeFix() {
  const time = new Date();
  const hour = time.getHours();
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好';
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了'];
  const index = Math.floor(Math.random() * arr.length);
  return arr[index];
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents');
  event.initEvent('resize', true, true);
  event.eventType = 'message';
  window.dispatchEvent(event);
}

export function handleScrollHeader(callback) {
  let timer = 0;

  let beforeScrollTop = window.pageYOffset;
  callback = callback || function () {};
  window.addEventListener(
    'scroll',
    (event) => {
      clearTimeout(timer);
      timer = setTimeout(() => {
        let direction = 'up';
        const afterScrollTop = window.pageYOffset;
        const delta = afterScrollTop - beforeScrollTop;
        if (delta === 0) {
          return false;
        }
        direction = delta > 0 ? 'down' : 'up';
        callback(direction);
        beforeScrollTop = afterScrollTop;
      }, 50);
    },
    false
  );
}

export function isIE() {
  const bw = window.navigator.userAgent;
  const compare = (s) => bw.indexOf(s) >= 0;
  const ie11 = (() => 'ActiveXObject' in window)();
  return compare('MSIE') || ie11;
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return;
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id));
  }, timeout);
}
export function scorePassword(pass) {
  let score = 0;
  if (!pass) {
    return score;
  }
  // award every unique letter until 5 repetitions
  const letters = {};
  for (let i = 0; i < pass.length; i++) {
    letters[pass[i]] = (letters[pass[i]] || 0) + 1;
    score += 5.0 / letters[pass[i]];
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(pass),
    lower: /[a-z]/.test(pass),
    upper: /[A-Z]/.test(pass),
    nonWords: /\W/.test(pass),
  };

  let variationCount = 0;
  for (var check in variations) {
    variationCount += variations[check] === true ? 1 : 0;
  }
  score += (variationCount - 1) * 10;

  return parseInt(score);
}

/**
 * 生成随机密码（默认六位、大小写加数字）
 * @param {*} len
 * @returns
 */
export function generatePassword(len = 6) {
  const randomPwdStrs = 'qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM';
  const length = randomPwdStrs.length;
  let result = '';
  for (let i = 0; i < len; i++) {
    const index = Math.floor(Math.random() * length);
    result += randomPwdStrs[index];
  }
  return result;
}

Date.prototype.format = function (fmt = 'yyyy-MM-dd hh:mm:ss') {
  var o = {
    'y+': this.getMonth(), // 年
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
    }
  }
  return fmt;
};
export function getQueryParameters() {
  const url = window.location.href;
  const search = url.split('?')[1];
  if (!search) {
    return {};
  }
  return JSON.parse(
    '{"' +
      // decodeURIComponent(search)
      search.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +
      '"}'
  );
}

/**
 * 非递归广度优先搜索树
 * @param {*} jsonTree
 * @param {*} callback
 * @param {*} key
 */
export function breadFirstTree(jsonTree, callback, key) {
  if (!jsonTree) return;
  let array = [];
  if (typeof jsonTree === 'object' && jsonTree.constructor === Object.prototype.constructor) {
    array.push(jsonTree);
  } else if (Array.isArray(jsonTree)) {
    array = jsonTree;
  } else {
    return;
  }

  let stack = [];

  // 先将第一层节点放入栈
  for (let i = 0, len = array.length; i < len; i++) {
    stack.push(array[i]);
  }

  let jn;

  while (stack.length) {
    jn = stack.shift();

    const re = callback(jn, array);
    if (!re) {
      return false;
    }
    if (re !== -1 && jn[key] && jn[key].length > 0) {
      stack = stack.concat(jn[key]);
    }
  }
}

/**
 * 单位转换成可读形式
 * @param {*} bytes
 * @returns
 */
export function formatBytes(bytes) {
  if (bytes === 0) return '0B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  const size = parseFloat((bytes / Math.pow(k, i)).toFixed(2));
  return size + sizes[i];
}

/**
 * 生成uuid
 * @returns
 */
export function generateUUID() {
  let d = new Date().getTime();
  if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
    d += performance.now(); // use high-precision timer if available
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (d + Math.random() * 16) % 16 | 0;
    d = Math.floor(d / 16);
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
  });
}

/**
 * 获取文件扩展名
 * @param {*} fileName
 * @param {*} toUpperCase 是否要转大写
 * @returns
 */
export function getFileExtend(fileName, toUpperCase = false) {
  if (!fileName || fileName.indexOf('.') === -1) {
    return '';
  }
  const ext = fileName.split('.').pop().toLowerCase();
  return toUpperCase ? ext.toUpperCase() : ext;
}

/**
 * 将url对应的文件转化成blob对象
 * @param {*} url
 * @returns
 */
export function urlToBlob(url) {
  return fetch(url)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`Failed to load ${url} with status ${response.status}`);
      }
      return response.blob();
    })
    .catch(() => {
      throw new Error(`Failed to load ${url}`);
    });
}

/**
 * 读取文件流内容
 * @param {*} buffer
 * @returns
 */
export function readFileText(buffer) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (loadEvent) => resolve(loadEvent.target.result);
    reader.onerror = (e) => reject(e);
    reader.readAsText(new Blob([buffer]), 'utf-8');
  });
}

/**
 * 将url对应的文件转化成arraybuffer
 * @param {*} url
 * @returns
 */
export function urlToArrayBuffer(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(xhr.statusText);
      }
    };
    xhr.onerror = () => {
      reject(xhr.statusText);
    };
    xhr.send();
  });
}

/**
 * 判断一个字符串是不是JSON格式的
 * @param {*} str
 * @returns
 */
export function isJSONString(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * 查找树
 * @param {*} tree 
 * @param {*} predicate 
 * @returns 
 */
export function findTreeNode(tree, predicate) {
  if (Array.isArray(tree)) {
    return filter(tree);
  } else {
    tree.children = filter(tree.children);
    return tree;
  }

  function filter(nodes) {
    if (!nodes?.length) {
      return nodes;
    }
    return nodes.filter((it) => {
      const children = filter(it.children);
      if (predicate(it) || children?.length) {
        it.children = children;
        return true;
      }
      return false;
    });
  }
}
